package algorithm;

import java.util.Arrays;

/**
 * User: Asuka
 * Date: 11-3-31
 * Time: 下午12:27
 */
public class ArrayExchange {

    public static void main(String[] args) {
        int[] arr1 = {1, 2, 3, 4, 5, 11, 12};
        int[] arr2 = {13, 14, 15, 100, 100, 101, 170};
        ArrayExchange arrayExchange = new ArrayExchange();
        arrayExchange.exchange(arr1, arr2);
        System.out.println(Arrays.toString(arr1));
        System.out.println(Arrays.toString(arr2));
    }

    public void exchange(int[] array, int[] another) {
        int[] merged = merge(array, another);
        Arrays.sort(merged);
        System.out.println(Arrays.toString(merged));
        int sumArray, sumAnother, arrayIndex, anotherIndex;
        sumArray = sumAnother = arrayIndex = anotherIndex = 0;
        for (int i = merged.length - 1; i >= 0; i--) {
            if (sumArray <= sumAnother && arrayIndex < array.length) {
                array[arrayIndex++] = merged[i];
                sumArray += merged[i];
            } else if (anotherIndex < another.length) {
                another[anotherIndex++] = merged[i];
                sumAnother += merged[i];
            } else {
                array[arrayIndex++] = merged[i];
                sumArray += merged[i];
            }
        }
    }

    private int[] merge(int[] array, int[] another) {
        int[] result = new int[array.length + another.length];
        int i;
        for (i = 0; i < array.length; i++) {
            result[i] = array[i];
        }
        for (int j = 0; j < another.length; j++, i++) {
            result[i] = another[j];
        }
        return result;
    }
}
